package com.Ahmad.FingerLock;

import java.sql.Time;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

    private KeyguardManager keyguardManager;
    KeyguardManager.KeyguardLock lock;
    ImageView imgScanLine;
    ImageView imgTouchBox;
    TextView edtUserName;
    TextView edtFileId;
    private Animation animScanner;
    RelativeLayout RLayout;
    private boolean readyForScan = true;
    private int touchCounter = 0;
    private Handler mHandler = new Handler();
    protected boolean PM;
    protected String strMins;
    protected String strHours;
    protected TextView txtClock;
    protected TextView txtDate;
    private Object dayOfMonth;
    private String dayOfTheWeek;
    private String monthOfYear;

    Calendar cal = Calendar.getInstance();
    SharedPreferences mPref;

    MediaPlayer ringDenied;
    MediaPlayer ringGranted;
    MediaPlayer ringScan;
    MediaPlayer ringCheckDb;
    MediaPlayer ringScanDb;

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        getWindow().setType(lp.type);
        mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        ringDenied = MediaPlayer.create(this, R.raw.access_denied);
        ringGranted = MediaPlayer.create(this, R.raw.access_granted);
        ringScan = MediaPlayer.create(this, R.raw.scaningline);
        ringScanDb = MediaPlayer.create(this, R.raw.scanning);
        ringCheckDb = MediaPlayer.create(this, R.raw.comparing_database);

        LayoutInflater inflater = getLayoutInflater();
        RLayout = (RelativeLayout) inflater.inflate(R.layout.scan, null);
        setContentView(RLayout);
        if (mPref.getBoolean(Constant.ENABLE_CLOCK, true)) {
            keyguardManager = ((KeyguardManager) getSystemService("keyguard"));
            lock = this.keyguardManager.newKeyguardLock("keyguard");
            lock.disableKeyguard();
            ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE)).listen(new PhoneState(), PhoneStateListener.LISTEN_CALL_STATE);
        }
        txtClock = (TextView) findViewById(R.id.txtClock);
        txtDate = (TextView) findViewById(R.id.txtDate);
        edtUserName = (TextView) findViewById(R.id.username);
        edtFileId = (TextView) findViewById(R.id.fileid);

        imgScanLine = (ImageView) findViewById(R.id.imgScanLine);
        imgTouchBox = (ImageView) findViewById(R.id.touchBox);
        animScanner = AnimationUtils.loadAnimation(this, R.anim.anim_move);
        final AlphaAnimation localAlphaAnimation = new AlphaAnimation(0.0F, 1.0F);
        localAlphaAnimation.setDuration(200L);
        localAlphaAnimation.setFillAfter(true);

        imgTouchBox.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int boxTouchHeight = imgTouchBox.getMeasuredHeight() - imgScanLine.getHeight();
                float yDelta = 0;
                yDelta = (float) boxTouchHeight;
                final TranslateAnimation localTranslateAnimation = new TranslateAnimation(0, 0, 0, yDelta);
                localTranslateAnimation.setDuration(500);
                localTranslateAnimation.setRepeatCount(TranslateAnimation.INFINITE);
                localTranslateAnimation.setRepeatMode(TranslateAnimation.REVERSE);
                localTranslateAnimation.setFillAfter(true);
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    touchCounter = 0;
                    imgScanLine.startAnimation(localTranslateAnimation);
                    mHandler.removeCallbacks(mUpdateTask);
                    mHandler.postAtTime(mUpdateTask, 1000 + SystemClock.uptimeMillis());
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    imgScanLine.clearAnimation();
                    mHandler.removeCallbacks(mUpdateTask);
                    processFinish();
                }
                return true;
            }
        });
        updateDMY();
        Timer mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                TimerMethod();
            }
        }, 0L, 1000L);

    }

    public void initScan() {
        edtUserName.setVisibility(View.INVISIBLE);
        edtFileId.setVisibility(View.INVISIBLE);
        imgTouchBox.setBackground(getResources().getDrawable(R.drawable.finger_scan));
        readyForScan = true;
    }

    private Runnable finishTask = new Runnable() {
        public void run() {
            if (touchCounter == mPref.getInt(Constant.SCAN_COUNT, 3)) {
                finish();
            } else {
                initScan();
            }
        }
    };

    public void processFinish() {
        readyForScan = false;
        ringScan.pause();
        if (touchCounter == mPref.getInt(Constant.SCAN_COUNT, 3)) {
            imgTouchBox.setBackground(getResources().getDrawable(R.drawable.scan_match));
            if (mPref.getBoolean(Constant.ENABLE_SOUND, true)) {
                ringGranted.start();
            }
            edtUserName.setText(mPref.getString(Constant.NAME_USER, "anonymous"));
            edtFileId.setText(mPref.getString(Constant.SPECIAL_NUMBER, "xxxx"));
            edtUserName.setVisibility(View.VISIBLE);
            edtFileId.setVisibility(View.VISIBLE);
            mHandler.postDelayed(finishTask, 1000);
        } else {
            imgTouchBox.setBackground(getResources().getDrawable(R.drawable.scan_mismatch));
            if (mPref.getBoolean(Constant.ENABLE_SOUND, true)) {
                ringDenied.start();
            }
            if (mPref.getBoolean(Constant.ENABLE_VIBRATION, true)) {
                Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                vibrator.vibrate(300);
            }
            mHandler.postDelayed(finishTask, 1000);
        }
    }

    public void updateDMY() {

        int i = new Time(System.currentTimeMillis()).getHours();
        int j = new Time(System.currentTimeMillis()).getMinutes();
        this.PM = false;
        this.strHours = String.valueOf(i);
        this.strMins = String.valueOf(j);
        if (i >= 13) {
            i -= 12;
            this.strHours = String.valueOf(i);
            this.PM = true;
        }
        if (i == 0)
            this.strHours = String.valueOf(12);
        if (j < 10)
            this.strMins = ("0" + String.valueOf(j));
        if (PM)
            this.txtClock.setText(this.strHours + ":" + this.strMins + " PM");
        else {
            this.txtClock.setText(this.strHours + ":" + this.strMins + " AM");
        }
        int k = cal.get(Calendar.DAY_OF_WEEK);
        int m = 1 + cal.get(Calendar.MONTH);
        dayOfMonth = String.valueOf(cal.get(Calendar.DAY_OF_MONTH));

        dayOfTheWeek = "Monday";
        if (k == 1) {
            this.dayOfTheWeek = "Sunday";
        } else if (k == 2) {
            this.dayOfTheWeek = "Monday";
        } else if (k == 3) {
            this.dayOfTheWeek = "Tuesday";
        } else if (k == 4) {
            this.dayOfTheWeek = "Wednesday";
        } else if (k == 5) {
            this.dayOfTheWeek = "Thursday";
        } else if (k == 6) {
            this.dayOfTheWeek = "Friday";
        } else if (k == 7) {
            this.dayOfTheWeek = "Saturday";
        }

        if (m == 1)
            this.monthOfYear = "Jan";
        else if (m == 2)
            this.monthOfYear = "Feb";
        else if (m == 3)
            this.monthOfYear = "Mar";
        else if (m == 4)
            this.monthOfYear = "Apr";
        else if (m == 5)
            this.monthOfYear = "May";
        else if (m == 6)
            this.monthOfYear = "Jun";
        else if (m == 7)
            this.monthOfYear = "Jul";
        else if (m == 8)
            this.monthOfYear = "Aug";
        else if (m == 9)
            this.monthOfYear = "Sep";
        else if (m == 10)
            this.monthOfYear = "Oct";
        else if (m == 11)
            this.monthOfYear = "Nov";
        else if (m == 12)
            this.monthOfYear = "Dec";
        else if (m == 1)
            this.monthOfYear = "Jan";
        txtDate.setText(dayOfTheWeek + ", " + monthOfYear + " " + dayOfMonth);
    }

    private void TimerMethod() {
        runOnUiThread(this.Timer_Tick);
    }

    private Runnable mUpdateTask = new Runnable() {
        public void run() {
            if ((readyForScan) && (15 > touchCounter)) {
                if (mPref.getBoolean(Constant.ENABLE_SOUND, true)) {
                    ringScan.start();
                }
                touchCounter = touchCounter + 1;
                if (touchCounter > 0) {
                    if (mPref.getBoolean(Constant.ENABLE_VIBRATION, true)) {
                        Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                        vibrator.vibrate(300);
                    }
                }
                Log.i("touchCounter", touchCounter + "");
                mHandler.postAtTime(this, 1000 + SystemClock.uptimeMillis());

            }
        }
    };

    @Override
    protected void onDestroy() {
        if (this.ringDenied.isPlaying())
            this.ringDenied.stop();
        if (this.ringGranted.isPlaying())
            this.ringGranted.stop();
        if (this.ringScan.isPlaying())
            this.ringScan.stop();
        if (this.ringCheckDb.isPlaying())
            this.ringCheckDb.stop();
        if (this.ringCheckDb.isPlaying())
            this.ringCheckDb.stop();
        this.ringDenied.release();
        this.ringGranted.release();
        this.ringScan.release();
        this.ringCheckDb.release();
        this.ringCheckDb.release();
        super.onDestroy();
    }

    @Override
    public void onAttachedToWindow() {

        super.onAttachedToWindow();
    }

    @Override
    public void onBackPressed() {
        // if (!mPref.getBoolean(Constant.ENABLE_CLOCK, true)) {
        // if (this.ringDenied.isPlaying())
        // this.ringDenied.stop();
        // if (this.ringGranted.isPlaying())
        // this.ringGranted.stop();
        // if (this.ringScan.isPlaying())
        // this.ringScan.stop();
        // if (this.ringCheckDb.isPlaying())
        // this.ringCheckDb.stop();
        // if (this.ringCheckDb.isPlaying())
        // this.ringCheckDb.stop();
        // finish();
        // } else {
        //
        // }
    }

    private Runnable Timer_Tick = new Runnable() {

        public void run() {
            int i = new Time(System.currentTimeMillis()).getHours();
            int j = new Time(System.currentTimeMillis()).getMinutes();
            PM = false;
            strHours = String.valueOf(i);
            strMins = String.valueOf(j);
            if (i >= 13) {
                i -= 12;
                strHours = String.valueOf(i);
                PM = true;
            }
            if (i == 0 && j == 0) {
                updateDMY();
            }
            if (i == 0)
                strHours = String.valueOf(12);
            if (j < 10)
                strMins = ("0" + String.valueOf(j));
            if (PM) {
                txtClock.setText(strHours + ":" + strMins + " PM");
            } else {
                txtClock.setText(strHours + ":" + strMins + " AM");
            }
        }
    };

    public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_HOME) {
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return true;
    };

    public final class PhoneState extends PhoneStateListener {
        private PhoneState() {
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);
            switch (state) {
            case TelephonyManager.CALL_STATE_OFFHOOK:
                try {
                    MainActivity.this.stopService(new Intent(MainActivity.this, MyLockServer.class));
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    MainActivity.this.stopService(new Intent(MainActivity.this, MyLockServer.class));
                }
                break;
            case TelephonyManager.CALL_STATE_RINGING:
                try {
                    MainActivity.this.stopService(new Intent(MainActivity.this, MyLockServer.class));
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    MainActivity.this.stopService(new Intent(MainActivity.this, MyLockServer.class));
                }
                break;
            case TelephonyManager.CALL_STATE_IDLE:
                MainActivity.this.startService(new Intent(MainActivity.this, MyLockServer.class));
                break;
            default:
                break;
            }
        }

    }

}
